import {
    x as C,
    r as ae,
    i as u,
    o as i,
    a as z,
    m as e,
    l as withCtx,
    k as y,
    F as J,
    j as X,
    b as f,
    t as V,
    e as s,
    O as K,
    P as R,
    Q as ee,
    B as g,
} from "./index-abba05ce.js";

const Ye = {class: "admin-lists", style: {width: "100%"}},
    Ze = {class: "border-none mt-2"},
    Je = {class: "d-flex justify-content-between"},
    Xe = {class: "filters"},
    Ke = {class: "border-none mt-3"},
    Qe = {class: "d-flex justify-content-end mt-4"};

const STATUS_OPTIONS = [
    {label: "全部状态", value: ""},
    {label: "正常", value: 1},
    {label: "隐藏", value: 2},
    {label: "待审核", value: 3},
];

const formatStatusText = (status) => {
    switch (status) {
        case 1:
            return "正常";
        case 2:
            return "隐藏";
        case 3:
            return "待审核";
        default:
            return "-";
    }
};

const formatTimestamp = (value) => {
    if (!value) return "-";
    const timestamp = String(value).length === 10 ? Number(value) * 1e3 : Number(value);
    if (!timestamp || Number.isNaN(timestamp)) return "-";
    const date = new Date(timestamp);
    if (Number.isNaN(date.getTime())) return "-";
    const pad = (num) => `${num}`.padStart(2, "0");
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};

const et = {
    __name: "index",
    setup() {
        const filters = ae({id: "", title: "", category_id: "", status: ""});
        const tableData = C([]);
        const categories = C([]);
        const loading = C(!1);
        const pagination = ae({page: 1, pageSize: 20, total: 0});

        const buildParams = () => {
            const params = {
                page: pagination.page,
                page_size: pagination.pageSize,
            };
            if (filters.id) params.id = filters.id;
            if (filters.title) params.title = filters.title;
            if (filters.category_id) params.category_id = filters.category_id;
            if (filters.status !== "") params.status = filters.status;
            return params;
        };

        const fetchList = async () => {
            loading.value = !0;
            try {
                console.log("调用fetchList");
                console.log("请求参数:", buildParams());
                // 直接使用fetch API请求数据，注意使用正确的接口路径/science/api/list
                const params = new URLSearchParams(buildParams());
                const response = await fetch(`/science/category/list?${params}`, {
                    method: "GET",
                    headers: {"Content-Type": "application/json"}
                });
                const res = await response.json();
                console.log("接口响应:", res);
                if (res.code !== 200 && res.code !== 0) {
                    R.msgError(res.msg || "获取列表失败");
                    return;
                }
                const data = res.data || {};
                console.log("响应数据:", data);
                tableData.value = data.data || [];
                console.log("表格数据:", tableData.value);
                pagination.total = data.total || 0;
                console.log("总条数:", pagination.total);
                pagination.page = data.page || pagination.page;
                pagination.pageSize = data.pageSize || pagination.pageSize;
            } catch (err) {
                console.error("fetch science list error", err);
                R.msgError("获取列表失败");
            } finally {
                loading.value = !1;
            }
        };

        // 添加处理添加按钮点击事件
        const handleAdd = () => {
            // 编辑功能，跳转到编辑页面
            window.location.href = new URL(`/science/category/edit`, window.location.origin).href;

        };

        // 编辑功能
        const handleEdit = (row) => {
            // 编辑功能，跳转到编辑页面
            console.log("编辑科学知识", row);
            // window.location.href = new URL(`science/category/edit?id=${row.id}&name=${encodeURIComponent(row.name)}`,window.location.origin).href;
       
            window.location.href = new URL(`/science/category/edit?id=${row.id}&view=1`, window.location.origin).href;
          };

        // 查看详情
        const handleView = (row) => {
            // 查看详情功能，跳转到编辑页面但可能需要设置为只读模式
            console.log("查看科学知识详情", row);
            window.location.href = new URL(`/science/category/edit?id=${row.id}&view=1`, window.location.origin).href;
        };

        const handleStatusChange = async (row) => {
            try {
                // 切换状态功能
                const newStatus = row.status === 1 ? 2 : 1;
                const res = await K.category.update({
                    id: row.id,
                    status: newStatus
                });
                if (res.error) {
                    R.msgError(res.msg || "状态更新失败");
                    return;
                }
                R.msgSuccess("状态更新成功");
                fetchList(); // 重新获取列表数据
            } catch (err) {
                console.error("update status error", err);
                R.msgError("状态更新失败");
            }
        };

        const fetchCategories = async () => {
            try {
                const response = await fetch("/science/api/categories");
                const json = await response.json();
                if ((json.code === 200 || json.code === 0) && Array.isArray(json.data)) {
                    categories.value = json.data;
                }
            } catch (err) {
                console.error("fetch science categories error", err);
            }
        };

        const handleSearch = () => {
            pagination.page = 1;
            fetchList();
        };

        const resetFilters = () => {
            filters.id = "";
            filters.title = "";
            filters.category_id = "";
            filters.status = "";
            pagination.page = 1;
            fetchList();
        };

        const handlePageChange = (page) => {
            pagination.page = page;
            fetchList();
        };

        const handleSizeChange = (size) => {
            pagination.pageSize = size;
            pagination.page = 1;
            fetchList();
        };

        fetchCategories();
        fetchList();

        // 删除功能
        const handleDelete = async (row) => {
            try {
                // 使用 window.confirm 替代 Vue 的 $confirm
                const confirmResult = window.confirm('确定要删除这条记录吗？删除后将无法恢复！');
                console.error('row', row);
                if (confirmResult) {
                    // 调用删除API
                    const res = await K.category.delete({id: row.id});
                    if (res.error) {
                        R.msgError(res.msg || '删除失败');
                        return;
                    }

                    R.msgSuccess('删除成功');
                    fetchList(); // 重新获取列表数据
                }
            } catch (err) {
                console.error('delete error', err);
                R.msgError('删除失败');
            }
        };

        return {
            filters,
            tableData,
            categories,
            loading,
            pagination,
            handleSearch,
            resetFilters,
            handlePageChange,
            handleSizeChange,
            handleAdd,
            handleEdit,
            handleView,
            handleStatusChange,
            handleDelete,
        };
    },
    render() {
        const d = this,
            a = u("el-card"),
            w = u("el-form"),
            p = u("el-form-item"),
            k = u("el-input"),
            b = u("el-select"),
            h = u("el-option"),
            q = u("el-button"),
            N = u("el-table"),
            m = u("el-table-column"),
            $ = u("el-tag"),
            P = u("el-image"),
            L = u("el-pagination"),
            T = ee("loading");
        return (
            i(),
                z("div", Ye, [
                    e(
                        a,
                        {class: "border-none mt-2", shadow: "never"},
                        {
                            default: withCtx(() => [
                                f("div", Je, [
                                    e(
                                        w,
                                        {model: d.filters, inline: ""},
                                        {
                                            default: withCtx(() => [e(p, {label: "ID", prop: "id"}, {
                                                    default: withCtx(() => [e(k, {
                                                            modelValue: d.filters.id,
                                                            "onUpdate:modelValue": d.$_id || (d.$_id = (t) => (d.filters.id = t)),
                                                            clearable: "",
                                                            placeholder: "请输入ID",
                                                            onKeyup:
                                                                d.$_enterId ||
                                                                (d.$_enterId = (t) =>
                                                                    t.key === "Enter" && d.handleSearch()),
                                                        },
                                                        null,
                                                        8,
                                                        ["modelValue", "onKeyup"],
                                                    ),
                                                    ]),
                                                    _: 1,
                                                },
                                            ),
                                                e(p, {label: "标题", prop: "title"}, {
                                                        default: withCtx(() => [e(k, {
                                                                modelValue: d.filters.title,
                                                                "onUpdate:modelValue": d.$_title || (d.$_title = (t) => (d.filters.title = t)),
                                                                clearable: "",
                                                                placeholder: "请输入标题关键词",
                                                                onKeyup: d.$_enterTitle || (d.$_enterTitle = (t) =>
                                                                    t.key === "Enter" && d.handleSearch()),
                                                            },
                                                            null,
                                                            8,
                                                            ["modelValue", "onKeyup"],
                                                        ),
                                                        ]),
                                                        _: 1,
                                                    },
                                                ),
                                                
                                                e(p, {style: {"margin-right": "0"}}, {
                                                        default: withCtx(() => [e(q, {
                                                                type: "primary",
                                                                icon: "Search",
                                                                onClick: d.handleSearch,
                                                            },
                                                            {default: withCtx(() => [s("查询")]), _: 1,},
                                                            8,
                                                            ["onClick"],
                                                        ),
                                                            e(
                                                                q,
                                                                {icon: "Refresh", onClick: d.resetFilters},
                                                                {
                                                                    default: withCtx(() => [s("重置")]),
                                                                    _: 1,
                                                                },
                                                                8,
                                                                ["onClick"],
                                                            ),
                                                        ]),
                                                        _: 1,
                                                    },
                                                ),
                                            ]),
                                            _: 1,
                                        },
                                        8,
                                        ["model"],
                                    ),
                                    e(q, {
                                        type: "primary",
                                        onClick: () => d.handleAdd()
                                    }, {
                                        default: withCtx(() => [s("新增")]),
                                        _: 1,
                                    }, 8, ["onClick"],),
                                ]),
                            ]),
                            _: 1,
                        },
                    ),
                    e(
                        a,
                        {class: "border-none mt-3", shadow: "never", style: {width: "100%"}},
                        {
                            default: withCtx(() => [
                                g(
                                    e(
                                        N,
                                        {
                                            data: d.tableData,
                                            size: "large",
                                            stripe: "",
                                            "row-key": "id",
                                            width: "100%",
                                            "header-cell-style": {
                                                background: "var(--el-bg-color-page)",
                                            },
                                        },
                                        {
                                            default: withCtx(() => [
                                                e(m, {prop: "id", label: "ID", width: "60", align: "center"}),
                                                e(m, {
                                                    prop: "name",
                                                    label: "名称",
                                                    width: "300",
                                                    "show-overflow-tooltip": "",
                                                    formatter: (row) => row.name || '未命名',
                                                    align: "center"
                                                }),
                                                e(
                                                    m,
                                                    {
                                                        prop: "update_time",
                                                        label: "更新时间",
                                                        width: "200",
                                                        formatter: (row) => row.update_time || '-',
                                                        align: "center",
                                                        'show-overflow-tooltip': ''
                                                    },
                                                ),

                                                e(
                                                    m,
                                                    {label: "操作", width: "200", fixed: "right", align: "center"},
                                                    {
                                                        default: withCtx(({row: t}) => [
                                                            e(
                                                                q,
                                                                {
                                                                    type: "success",
                                                                    size: "small",
                                                                    style: {marginRight: "10px"},
                                                                    onClick: () => d.handleEdit(t)
                                                                },
                                                                {
                                                                    default: withCtx(() => [s("编辑")]),
                                                                    _: 1,
                                                                },
                                                                8,
                                                                ["onClick"],
                                                            ),
                                                            e(
                                                                q,
                                                                {
                                                                    type: "danger",
                                                                    size: "small",
                                                                    onClick: () => d.handleDelete(t)
                                                                },
                                                                {
                                                                    default: withCtx(() => [s("删除")]),
                                                                    _: 1,
                                                                },
                                                                8,
                                                                ["onClick"],
                                                            )
                                                        ]),
                                                        _: 1,
                                                    },
                                                ),

                                            ]),
                                            _: 1,
                                        },
                                        8,
                                        ["data", "header-cell-style"],
                                    ),
                                    [[T, d.loading]],
                                ),
                                f("div", Qe, [
                                    e(
                                        L,
                                        {
                                            background: "",
                                            layout: "total, sizes, prev, pager, next, jumper",
                                            total: d.pagination.total,
                                            "page-sizes": [10, 20, 50, 100],
                                            "current-page": d.pagination.page,
                                            "page-size": d.pagination.pageSize,
                                            onCurrentChange: d.handlePageChange,
                                            onSizeChange: d.handleSizeChange,
                                            "hide-on-single-page": false,
                                        },
                                        null,
                                        8,
                                        [
                                            "total",
                                            "current-page",
                                            "page-size",
                                            "onCurrentChange",
                                            "onSizeChange",
                                            "hide-on-single-page",
                                        ],
                                    ),
                                ]),
                            ]),
                            _: 1,
                        },
                    ),
                ])
        );
    },
};

export {et as default};
